import Head from 'next/head';
import { AdminLayout } from '@/components/Layout';
import dynamic from 'next/dynamic';
import { useState, useEffect } from 'react';
import { requestMsg } from '@/components/server/utils/request';
import type { Data } from '@/pages/api/post/categories/list';

const DynamicEditor = dynamic(() => import('@/components/Editor'), {
  ssr: false,
});
import { useRouter } from 'next/router';
import { Data as PostData } from '@/pages/api/post/get';
import { Data as EditData } from '@/pages/api/post/edit';
import { getLangByIntl } from '@/components/utils/locale';
import { useIntl } from 'react-intl';
import {
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  PageContainer,
} from '@ant-design/pro-components';
import { Form, Button, Checkbox, Typography } from 'antd';
import { useCountdown } from '@/components/utils/useTimer';

export default function Index() {
  const router = useRouter();
  const intl = useIntl();
  const lang = getLangByIntl(intl);
  const [form] = Form.useForm();

  const [html, setHtml] = useState<string>('');
  const [id, setId] = useState<number>(0);
  const { countdown, setupCountdown, destroy } = useCountdown();
  const [checked, setChecked] = useState<boolean>(false);

  useEffect(() => {
    if (id <= 0) {
      return;
    }
    requestMsg<PostData>('/api/post/get', {
      method: 'get',
      params: { id },
      lang,
    }).then((res) => {
      form.setFieldsValue(res);
      const catIds: number[] = [];
      res.categories?.map((value) => {
        catIds.push(value.categoryId);
      });
      form.setFieldValue('categoryId', catIds);
      setHtml(res.content || '');
    });
  }, [id]); //eslint-disable-line
  useEffect(() => {
    const { id: queryId } = router.query;
    if (typeof queryId != 'string') {
      return;
    }
    if (parseInt(queryId) <= 0) {
      return;
    }
    setId(parseInt(queryId));
  }, [router.query]);
  useEffect(() => {
    if (countdown <= 0 && checked) {
      form.submit();
      setupCountdown(60);
    }
  }, [countdown]); //eslint-disable-line
  useEffect(() => {
    if (checked) {
      setupCountdown(60);
    } else {
      destroy();
    }
    return () => {
      destroy();
    };
  }, [checked]); //eslint-disable-line
  return (
    <>
      <Head>
        <link
          rel="shortcut icon"
          type="image/x-icon"
          href="https://unpkg.byted-static.com/latest/byted/arco-config/assets/favicon.ico"
        />
      </Head>
      <PageContainer
        footer={[
          <Typography.Text hidden={countdown <= 0} key={'post.tip'}>
            {countdown}秒后自动保存
          </Typography.Text>,
          <Checkbox
            key={'post.checked'}
            checked={checked}
            onChange={(value) => {
              setChecked(value.target.checked);
            }}
          >
            {'自动保存'}
          </Checkbox>,
          <Button
            key="post.submit"
            type="primary"
            onClick={() => {
              form.submit();
            }}
          >
            提交
          </Button>,
        ]}
      >
        <ProForm
          form={form}
          onFinish={async (value) => {
            requestMsg<EditData>('/api/post/edit', {
              method: 'post',
              data: value,
            }).then((res) => {
              if (id === 0) {
                setId(res.id);
              }
            });
          }}
          submitter={false}
        >
          <ProForm.Item name="id" hidden>
            <ProFormText></ProFormText>
          </ProForm.Item>
          <ProForm.Item
            name="title"
            label={intl.formatMessage({ id: 'post.title' })}
          >
            <ProFormText></ProFormText>
          </ProForm.Item>
          <ProForm.Item name="categoryId">
            <ProFormSelect
              mode="multiple"
              request={async (params = {} as Record<string, any>) => {
                return requestMsg<Data>('/api/post/categories/list', {
                  method: 'post',
                  data: { page: params.current, size: params.pageSize },
                  lang,
                }).then((ret) => {
                  const d: Record<string, any>[] = [];
                  ret.categories?.map((value) => {
                    d.push({ value: value.id, label: value.cat });
                  });
                  return Promise.resolve(d);
                });
              }}
            ></ProFormSelect>
          </ProForm.Item>
          <ProForm.Item name="content" hidden>
            <ProFormTextArea></ProFormTextArea>
          </ProForm.Item>
          <ProForm.Item>
            <DynamicEditor
              html={html}
              setHtml={(html) => {
                form.setFieldValue('content', html);
              }}
              lang={lang.lang}
            ></DynamicEditor>
          </ProForm.Item>
        </ProForm>
      </PageContainer>
    </>
  );
}
Index.Layout = AdminLayout;
